package cn.edu.njust.chat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class ChatClientHandler extends ChannelInboundHandlerAdapter {

    private final ExecutorService executor = Executors.newSingleThreadExecutor();

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        log.info("加入聊天室成功");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 防止阻塞IO线程
        executor.execute(new Runnable() {
            @Override
            public void run() {
                String message;
                Scanner in = new Scanner(System.in);
                while (true) {
                    message = in.nextLine();

                    if (!Objects.equals(message, "exit"))
                        ctx.writeAndFlush(message);
                    else {
                        ctx.close();
                        log.info("退出聊天室");
                        return;
                    }
                }
            }
        });
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info((String) msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
    }
}
